//
//  MXSTabBar.swift
//  weibo
//
//  Created by 孙飞 on 15/12/5.
//  Copyright © 2015年 Sunfei. All rights reserved.
//

import UIKit

class MXSTabBar: UITabBar {
    
    // weak var delegatess: HMTabBarDeletate?
    
    var composeButtonClosure: (()->())?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    // 重写 init:frame，必须要实现 init:coder
    // 如果View 从 xib / sb 里面加载
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupUI()
    }
    
    //按钮
    lazy var composeButton: UIButton = {
        
        let button = UIButton()
        
        button.addTarget(self, action: "composeButtonClick", forControlEvents: UIControlEvents.TouchUpInside)
        // 背景图片
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: .Normal)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: .Highlighted)
        
        // 状态图片
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        
        button.sizeToFit()
        
        return button
    }()
    
    // MARK: - 更新
    func setupUI(){
        backgroundImage = UIImage(named: "tabbar_background")
        
        addSubview(composeButton)
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        // 子控件居中,不能使用父控件的center
        composeButton.center = CGPoint(x: frame.width * 0.5, y: frame.height * 0.5)
        
        let childW = frame.width / 5
        
        var index = 0
        
        for childView in subviews {
            // UITabBarButton 是一个私有的控件,不能直接获取 class
            if childView.isKindOfClass(NSClassFromString("UITabBarButton")!) {
                
                let x = CGFloat(index) * childW
                childView.frame = CGRect(x: x, y: 0, width: childW, height: frame.height)
                
                index++
                
                // 隔到 编辑按钮
                if index == 2 {
                    index++
                }
            }
        }
    }
    
    // MARK: - 点击编辑按钮
    @objc private func composeButtonClick(){
        print("点击编辑按钮")
        
        composeButtonClosure?()
    }
    
    

    
}
